﻿using ContactSMS.Domain;
using ContactSMS.Domain.Entity;
using ContactSMS.Infrastructure.dbContexts;
using Microsoft.EntityFrameworkCore;

namespace ContactSMS.Infrastructure
{
    public class PhoneRepository : IPhoneRepository
    {
        private readonly ContactDbContexts _contactDbContexts;

        public PhoneRepository(ContactDbContexts contactDbContexts)
        {
            this._contactDbContexts = contactDbContexts;
        }

        public async Task<Phone?> AddPhoneAsync(Phone Phone)
        {
            await _contactDbContexts.Phones.AddAsync(Phone);
            await _contactDbContexts.SaveChangesAsync();
            return Phone;
        }

        public async Task<List<Phone>?> DeletePhoneByContactIdAsync(long ContactId)
        {

            var result = await GetPhoneByContactIdAsync(ContactId);
            if (result != null)
            {
                _contactDbContexts.Phones.RemoveRange(result);
                await _contactDbContexts.SaveChangesAsync();
                return result;
            }
            return null;
        }

        public async Task<List<Phone>?> DeletePhoneByContactIdsAsync(long[] ContactId)
        {
            var phonesToDelete = await _contactDbContexts.Phones
                                    .Where(phone => ContactId.Contains(phone.ContactId))
                                    .ToListAsync();
            _contactDbContexts.Phones.RemoveRange(phonesToDelete);
            await _contactDbContexts.SaveChangesAsync();
            return phonesToDelete;
        }

        public async Task<List<Phone>?> GetPhoneByContactIdAsync(long ContactId)
        {
            var result = await _contactDbContexts.Phones.Where(o => o.ContactId == ContactId).ToListAsync();
            return result;
        }

        public async Task<Phone> GetPhoneByIdAsync(long id)
        {
            var result = await _contactDbContexts.Phones.Where(o => o.Id == id).FirstOrDefaultAsync();
            return result;
        }

        public async Task<Phone> GetPhoneByMobileAsync(string mobile)
        {
            var result = await _contactDbContexts.Phones.Where(o => o.Mobile == mobile).FirstOrDefaultAsync();
            return result;
        }
    }
}
